package com.example.demo.controller;

import com.example.demo.pojo.LoginInformation;
import com.example.demo.pojo.PublicFields;
import com.example.demo.pojo.Result;
import com.example.demo.pojo.dto.UserDTO;
import com.example.demo.pojo.entity.User;
import com.example.demo.pojo.vo.UserVO;
import com.example.demo.properties.JwtProperties;
import com.example.demo.service.imply.IUserServiceImply;
import com.example.demo.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户相关接口")
@RequiredArgsConstructor
@CrossOrigin(origins = {"http://localhost:8080"}, allowCredentials = "true")
public class UserController {
    private final IUserServiceImply userService;
    private final JwtProperties jwtProperties;
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<LoginInformation> login(@RequestBody UserDTO userDTO) {

        User user = userService.login(userDTO);
        if(user!=null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getId());
            String jwt = JwtUtil.createJwt(claims);
            LoginInformation loginInformation = new LoginInformation();
            loginInformation.setUserId(user.getId());
            loginInformation.setToken(jwt);
            return Result.success(loginInformation);
        }
        return Result.error("登录失败");
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<UserVO> register(@RequestBody UserDTO userDTO){
        userService.register(userDTO,PublicFields.newInstance());
        return null;
    }

    @ApiOperation("根据用户id查询用户")
    @PostMapping("/{id}")
    public Result<UserVO> getUserByUserId(@PathVariable Long id){

        UserVO userVO = userService.getUserByUserId(id);

        return Result.success(userVO);
    }

    @ApiOperation("用户退出")
    @PutMapping("/logout")
    public Result logout(){

        userService.logout();
        return Result.success("退出登录成功");
    }
}
